﻿using AutoMapper;
using B.Auth.APi.Application.Command.Leaves;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;

namespace B.Auth.APi.Application.CommandHand.Leaves
{
    public class LeaveAddCommandHand : IRequestHandler<LeaveAddCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LeaveModel> _leave;
        private readonly IMapper mapper;

        public LeaveAddCommandHand(IBaseRepository<LeaveModel> leave, IMapper mapper)
        {
            _leave = leave;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(LeaveAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            var Leave = new LeaveModel();
            var leaves = mapper.Map<LeaveModel>(request);
            leaves.ShenType = 0;
            leaves.CreateUserName = "张三";
            leaves.CreateTime = DateTime.Now;
            leaves.WorkTime = GetworkTime(request.BeginTime, request.EndTime);
            leaves.AuditNowName = leaves.DepartmentHead.Split(',')[0];
            _leave.Add(leaves);
            result.Code = ApiEnum.ok;
         
            result.Message = "添加成功";
            result.data = 1;

            return Task.FromResult(result);
           
        }

        public int GetworkTime(DateTime BeginTime, DateTime Endtime)
        {
            var housetime = (int)(Endtime - BeginTime).TotalHours;
            if (housetime <= 8)
            {


                return housetime;
            }
            if (housetime > 8 && housetime <= 24)
            {
                return 8;
            }
            if (housetime > 24)
            {
                var housetime1 = housetime / 24;
                var housetime2 = housetime % 24;
                if (housetime2 <= 8)
                {


                    housetime2 = housetime2;
                }
                if (housetime2 > 8 && housetime < 24)
                {
                    housetime2 = 8;
                }
                housetime = housetime1 * 8 + housetime2;
                return housetime;

            }

            return housetime;
        }

    }

}
